﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Xenta.Utils;
using Xenta.Attributes;
using Xenta.Web.Controllers;

namespace Xenta.Web.Areas.System.Controllers
{
    [Authenticate, InRole("ADMIN")]
    public sealed class LookupAttributeController : ExtController
    {
        #region GET/POST Actions

        [HttpGet, RestoreState]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet, RestoreState]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost, PersistState]
        public ActionResult Create(int displayOrder, string[] flags)
        {
            try
            {
                var m = Svc.ProcessOperation("CreateLookupAttribute", new
                {
                    DisplayOrder = displayOrder,
                    Flags = flags.Merge(",")
                });
                return RedirectToAction(Loc.Act("Edit").Set(new
                {
                    id = JDM.Int32(m.EntityID)
                }));
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Create"));
        }

        [HttpGet, RestoreState]
        public ActionResult Edit(int id)
        {
            var m = Svc.ProcessOperation("GetLookupAttribute", new
            {
                EntityID = id
            }, new
            {
                DisclosureLevel = "Entire"
            });
            if(m == null)
                return HttpNotFound();
            return View(m);
        }

        [HttpPost, PersistState]
        public ActionResult Update(int id, int displayOrder, string[] flags)
        {
            try
            {
                Svc.ProcessOperation("UpdateLookupAttribute", new
                {
                    EntityID = id,
                    DisplayOrder = displayOrder,
                    Flags = flags.Merge(",")
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }

            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpGet, PersistState]
        public ActionResult Delete(int id)
        {
            try
            {
                Svc.ProcessOperation("DeleteLookupAttribute", new
                {
                    EntityID = id
                });
                return RedirectToAction(Loc.Act("Index"));
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpPost, PersistState]
        public ActionResult CreateTranslation(int attributeID, 
            int languageID, 
            string name, 
            string value)
        {
            try
            {
                Svc.ProcessOperation("CreateLookupAttributeTranslation", new
                {
                    HolderID = attributeID,
                    LanguageID = languageID,
                    Name = name,
                    Value = value
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id = attributeID
            }));
        }

        [HttpPost, PersistState]
        public ActionResult UpdateTranslation(int id, 
            int attributeID, 
            int languageID,
            string name,
            string value)
        {
            try
            {
                Svc.ProcessOperation("UpdateLookupAttributeTranslation", new
                {
                    EntityID = id,
                    LanguageID = languageID,
                    Name = name,
                    Value = value
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id = attributeID
            }));
        }

        [HttpGet, PersistState]
        public ActionResult DeleteTranslation(int id, int attributeID)
        {
            try
            {
                Svc.ProcessOperation("DeleteLookupAttributeTranslation", new
                {
                    EntityID = id
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id = attributeID
            }));
        }

        #endregion

        #region AJAX Actions

        [HttpPost]
        public ActionResult Grid(int? page,
            int? rows,
            string sord,
            string sidx, 
            string searchTerm,
            string flagMask)
        {
            page = page.HasValue ? page.Value - 1 : 0;
            rows = rows.HasValue ? rows.Value : 30;
            sord = sord.Equals("desc") ? "Descending" : "Ascending";

            var m = Svc.ProcessOperation("SearchLookupAttributes", new 
            {
                Term = new
                {
                    Expression = searchTerm
                },
                FlagMask = flagMask,
                Index = page * rows,
                Count = rows,
                SortBy = new[] 
                {
                    sidx
                },
                SortDir = sord
            }, new
            {
                DisclosureLevel = "Base",
                DisclosureOptions = new Dictionary<String, String>
                {
                    { "TranslatedTo", JDM.String(Svc.Localization.Language.Code) }
                }.Unload()
            });
            var data = new List<Object>();

            foreach(var i in m.Items)
            {
                var t_attr = (i.Translations as IEnumerable<dynamic>)
                    .SingleOrDefault(x => JDM.Int32(x.Language.EntityID) == 
                        JDM.Int32(Svc.Localization.Language.EntityID));
                data.Add(new[] { 
                    JDM.Int32(i.EntityID),
                    t_attr != null ? JDM.String(t_attr.Name) : String.Empty,
                    t_attr != null ? JDM.String(t_attr.Value) : String.Empty
                });
            }

            return Json(new
            {
                pageIndex = page + 1,
                pageCount = JDM.Int64(m.TotalCount) / rows + 1,
                totalCount = JDM.Int64(m.TotalCount),
                data = data.ToArray()
            });
        }

        [HttpPost]
        public ActionResult Autocomplete(string term, string flagMask)
        {
            var m = Svc.ProcessOperation("GetLookupAttributeDictionary", new
            {
                LanguageID = JDM.Int32(Svc.Localization.Language.EntityID),
                FlagMask = flagMask,
                Term = new
                {
                    Expression = String.Format("%{0}%", term)
                },
                Count = 10
            });
            var data = new List<Object>();

            foreach(var i in m.Items)
            {
                data.Add(new
                {
                    id = JDM.String(i.Key),
                    value = JDM.String(i.Value)
                });
            }
            return Json(data.ToArray());
        }

        #endregion
    }
}
